import React, { useState } from 'react';
import NumberField from '../../../../../../components/common/NumberField';
import StatefulCalculationCard from '../../../../../../components/common/StatefulCalculationCard';
import ExportData from '../../../../../../components/common/ExportCalculateData';
import type { ResultItem } from '../../../../../../../shared/types';

// 焊缝计算表单类型定义
export interface WeldFormValues { 
    strengthFactor: number,
    weldSize: number,
    weldLength: number,
    weldStrengthValue: number,
    axialForce: number,
}

// 焊缝计算结果类型定义
export interface WeldResult {
    weldStrength: number;
    isValid: boolean;
}

// 焊缝计算初始值配置
const initialValues: WeldFormValues = {
    strengthFactor: 1.22,
    weldSize: 6,
    weldLength: 150,
    weldStrengthValue: 160,
    axialForce: 100000,
};

// 焊缝计算卡片组件配置
const weldConfig = {
  key: 'Weld',
  label: '焊缝计算',
  formKey: 'crossing-weld-calculation',
  initialValues: initialValues,
  calculationType: 'truss-weld-calculation',
  resultFormatter: (data: WeldResult) => [
    { key: 'weldStrength', name: '焊缝应力', value: data.weldStrength, unit: 'MPa' },
    { key: 'isValid', name: '强度校核', value: data.isValid ? '满足' : '不满足', unit: '' },
  ],
  renderFormFields: () => (
    <>
      <NumberField name="strengthFactor" label="强度设计值增大系数" required min={0.1} max={10} step={0.01} tooltip="强度设计值增大系数，一般取1.22" />
      <NumberField name="weldSize" label="焊脚尺寸" required min={1} max={50} step={1} tooltip="焊脚尺寸，一般取6mm，单位为mm" />
      <NumberField name="weldLength" label="焊缝长度" required min={10} max={1000} step={10} tooltip="焊缝长度，一般取150mm，单位为mm" />
      <NumberField name="weldStrengthValue" label="角焊缝强度设计值" required min={10} max={500} step={5} tooltip="角焊缝强度设计值，Q235取160MPa，Q345取205MPa，单位为MPa" />
      <NumberField name="axialForce" label="轴力" required min={1000} max={1000000} step={1} tooltip="轴力，单位为N" />
    </>
  )
};

// 焊缝计算卡片组件实现
const WeldCard: React.FC = () => {
  const [lastResults, setLastResults] = useState<ResultItem[] | null>(null);
  return (
    <StatefulCalculationCard
      title={weldConfig.label}
      formKey={weldConfig.formKey}
      initialValues={weldConfig.initialValues}
      renderFormFields={weldConfig.renderFormFields}
      calculationType={weldConfig.calculationType}
      resultFormatter={(data) => {
        const results = weldConfig.resultFormatter(data);
        setLastResults(results);
        return results;
      }}
      columnCount={2} // 使用2列布局
      tableHeight={500} // 设置表格高度为500px
      exportComponent={(form) => (
        <ExportData
          siteName={weldConfig.label}
          inputs={form.getFieldsValue()}
          results={lastResults ? Object.fromEntries(lastResults.map(r => [r.key, r.value])) : {}}
          calculationType={weldConfig.calculationType}
        />
      )}
    >
    </StatefulCalculationCard>
  );
};

export default WeldCard;